package cn.liulin.java8.simplestudy;

import com.alibaba.fastjson.JSON;

import java.util.Iterator;

/**
 * cn.liulin.java8.simplestudy$
 *
 * @author ll
 * @date 2024-03-21 18:01:55
 **/
public class MyArrayList {
    // 原始数组，数组初始化需要设置长度，随便默认一个16
    public Object[] objects = new Object[16];
    // 我需要知道当前已经插入的位置index。默认为0
    public int index = 0;
    public boolean add(Object obj) {
        objects[index++] = obj;
        // 判断index长度是否等于数组初始化长度
        if (index == objects.length) {
            // 开始扩容，直接翻倍
            Object[] newObjects = new Object[objects.length * 2];
            System.arraycopy(objects, 0, newObjects, 0, index);
            objects = newObjects;
        }
        return true;
    }

    public Object get(int i) {
        if (i < 0 || i >= index) {
            throw new RuntimeException("查询异常");
        }
        return objects[i];
    }

    public Integer remove(int i) {
        if (i < 0 || i >= index) {
            throw new RuntimeException("删除异常");
        }
        Integer tmp = (Integer) objects[i];
        if (index - i - 1 > 0) {
            System.arraycopy(objects, i + 1, objects, i, index - i - 1);
        }
        objects[--index] = null;
        return tmp;
    }

    @Override
    public String toString() {
        if (index == 0) {
            return "[]";
        } else {
            StringBuilder sb = new StringBuilder();
            Iterator<Object> iterator = itr();
            sb.append("[");
            while (iterator.hasNext()) {
                sb.append(iterator.next());
                if (iterator.hasNext()) {
                    sb.append(",");
                }
            }
            sb.append("]");
            return sb.toString();
        }
    }

    private Iterator itr() {
        return new MyArrayListIterator();
    }

    public class MyArrayListIterator implements Iterator {

        private int cur;

        @Override
        public boolean hasNext() {
            return cur != index;
        }

        @Override
        public Object next() {
            if (cur == index) {
                throw new RuntimeException("越界异常");
            }
            return objects[cur++];
        }
    }

    public static void main(String[] args) {
        MyArrayList myArrayList = new MyArrayList();
        for (int i = 0; i < 100; i++) {
            myArrayList.add(i);
        }
        System.out.println(JSON.toJSONString(myArrayList));
        System.out.println(myArrayList.toString());
        for (int i = 0; i < 100; i++) {
            Integer remove = (Integer) myArrayList.remove(0);
            System.out.println(remove);
            System.out.println(myArrayList.toString());
        }
    }
}
